export function globalAnswerParse(content) {
  let globalAnswerArr = handleComponents(content);
  console.log(globalAnswerArr);
  let sesstionsAnswer = handleSessionAnswers(globalAnswerArr, content);
  console.log("sesstionsAnswer", sesstionsAnswer);
  return sesstionsAnswer;
}

/**
 * 4.对components进行处理
 * 区分结果页SDK与非结果页SDK组件数据处理
 * 结果页SDK标志：layout_mode === 'grid';
 *  结果页sdk渲染数据：遍历layout_data对每项进行处理;
 *      1. 遇到txt2组件，将txt2之前的组件渲染成一个结果页sdk组件
 *      2. 没有遇到txt2组件，将剩余组件染成一个结果页sdk组件
 *  非结果页sdk渲染：遍历components
 *      1.以txt2进行切分，txt2是一个单独的气泡
 * @param {*} content
 * @returns
 */
function handleComponents(content) {
  let globalAnswerArr = [];
  if (Array.isArray(content.components) && content.components.length > 0) {
    // 4.1.获取layout_mode和layout_data的数据
    const {
      page: { layout: { layout_mode = "", layout_data = "" } = {} } = {},
    } = content;
    // 保存layout_data数据
    let layoutData = "";
    if (isJson(layout_data)) {
      layoutData = JSON.parse(layout_data);
    }
    // 4.2.判断layout_data是否有值
    const isJGYSDK = isJgySdk(layoutData);
    if (isJGYSDK) {
      // 4.3.1.结果页sdk处理逻辑
      globalAnswerArr = handleJgySdk(layoutData, content);
    } else {
      // 4.3.2.非结果页sdk处理逻辑
      globalAnswerArr = handleUnJgySdk(content);
    }
  }
  return globalAnswerArr;
}
/**
 * 判断一个字符串是否是JOSN字符串
 * @param {*} str
 * @returns
 */
export function isJson(str) {
  if (typeof str == "string") {
    try {
      const obj = JSON.parse(str);
      if (typeof obj == "object" && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }
}

function isJgySdk(layoutData) {
  return layoutData.length > 0;
}

/**
 * 对结果页sdk的解析逻辑
 * 思路：根据layout_data进行数据处理，并以txt2进行切分
 * @param {*} layout_data
 * @param {*} content
 * @returns
 */
function handleJgySdk(layoutData, content) {
  let globalAnswerArr = [];
  // 记录layoutData组件
  let layoutDataArr = [];

  if (Array.isArray(layoutData)) {
    layoutData.map((item) => {
      if (item.showType === "txt2") {
        // 判断记录组件layoutDataArr中是否有值
        if (layoutDataArr.length > 0) {
          // 对layoutDataArr作数据处理，获取对应的components，放入globalAnswerArr中
          let answer = handleLayoutDataArr(layoutDataArr, content);
          globalAnswerArr.push(answer);
          // 清空layoutDataArr
          layoutDataArr = [];
        }

        // showType为txt2，在components中找到该组件，并放入globalAnswerArr中
        let componentItem;
        for (let i = 0; i < content.components.length; i++) {
          if (
            content.components[i] &&
            content.components[i].uuid === item.uuid
          ) {
            componentItem = content.components[i];
            break;
          }
        }
        if (componentItem && componentItem.data && componentItem.data.content) {
          const results = {};
          results["components"] = [componentItem];
          results["layout_data"] = JSON.parse(JSON.stringify(item));
          globalAnswerArr.push(results);
        }
      } else {
        // 遍历components，当components中有该组件时再去push
        if (
          content.components.findIndex(
            (componentsItem) => componentsItem.uuid === item.uuid
          ) > -1
        ) {
          layoutDataArr.push(item);
        }
      }
    });
    // 遍历完成，看layoutDataArr中是否还有值
    if (layoutDataArr.length > 0) {
      // 对layoutDataArr作数据处理
      let answer = handleLayoutDataArr(layoutDataArr, content);
      globalAnswerArr.push(answer);
    }
  }
  return globalAnswerArr;
}

/**
 * 对非结果页sdk的解析逻辑
 * 思路：遍历components，以txt2进行切分
 * @param {*} content
 * @returns
 */
function handleUnJgySdk(content) {
  let globalAnswerArr = [];
  // 记录组件
  let components = [];

  content.components.forEach((item, index) => {
    if (item.show_type === "txt2") {
      // 判断记录组件中是否有值
      if (components.length !== 0) {
        globalAnswerArr.push({
          components: [...components],
        });
        components = [];
      }
      if (item.data && item.data.content) {
        globalAnswerArr.push({
          components: [item],
        });
      }
    } else {
      components.push(item);
    }
  });
  // 遍历完成，看components中是否还有值存入globalAnswerArr中
  if (components.length !== 0) {
    globalAnswerArr.push({
      components: [...components],
    });
  }
  return globalAnswerArr;
}
/**
 * 处理结果页sdk，保存对应的components
 * 将layoutDataArr中的数据与components中的组件一一对应
 * @param {*} layoutDataArr
 * @param {*} content
 * @returns
 */
function handleLayoutDataArr(layoutDataArr, content) {
  let results = {
    components: [],
    layout_data: JSON.parse(JSON.stringify(layoutDataArr)),
  };

  fn(layoutDataArr, content);

  function fn(layoutDataArr, content) {
    let components = [];
    layoutDataArr.forEach((item, index) => {
      if (!Array.isArray(item) && item.uuid) {
        for (let i = 0; i < content.components.length; i++) {
          if (
            content.components[i] &&
            content.components[i].uuid &&
            content.components[i].uuid === item.uuid
          ) {
            components.push(content.components[i]);
          }
        }
      }
      if (components.length > 0) {
        results["components"].push(...components);
        components = [];
      }
      // 判断children是否存在
      if (item.children && item.children.length > 0) {
        fn(item.children, content);
      }
    });
  }
  return results;
}

/**
 * 将答案包裹成最终能渲染的格式
 * @param {*} data
 * @param {*} zhenguData
 * @returns
 */
function handleSessionAnswers(data, zhenguData) {
  let answers = [];
  if (data.length > 0) {
    for (let key in data) {
      // 定义session的格式
      let session = {
        components: [],
        page: {
          layout: {
            layout_data: "",
          },
        },
        global: {},
        show_type: "",
        delyTime: 0,
      };
      session.components = data[key].components;
      session.page = JSON.parse(JSON.stringify(zhenguData.page));
      if (data[key].layout_data) {
        session.page.layout.layout_data = JSON.stringify(data[key].layout_data);
      }
      session.global = zhenguData.global;
      // 给每个组件增加延迟时间
      session.delyTime = Number(key) * 100 + 100;
      data[key].components.forEach((item) => {
        if (item.show_type === "txt2") {
          session.show_type = "txt2";
        } else {
          session.show_type = "other";
        }
      });
      answers.push(session);
    }
  }
  return answers;
}
